package com.xinshujia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xinshujia.dao.RoleDao;
import com.xinshujia.dao.UserDao;
import com.xinshujia.dto.UserDTO;
import com.xinshujia.entity.UserEntity;
import com.xinshujia.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * *************************************
 * *   @author: 野狼上校               **
 * *   @since: 2024-07-15 19:36       **
 * *   @version: 1.0                  **
 * *************************************
 * <p>
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {
    private final UserDao userDao;
    private final RoleDao roleDao;

    public UserServiceImpl(UserDao userDao, RoleDao roleDao) {
        this.userDao = userDao;
        this.roleDao = roleDao;
    }

    /*新增用户*/
    @Override
    public boolean insert(UserEntity userEntity) {
        userEntity.setDeleted(true);
        int count = userDao.insert(userEntity);
        return count > 0;
    }

    /*根据Id删除用户（实际是更新操作）*/
    @Override
    public boolean deleteById(Long id) {
        if (id != null) {
            UserEntity userEntity = new UserEntity();
            userEntity.setId(id);
            userEntity.setDeleted(false);
            int count = userDao.updateById(userEntity);
            return count > 0;
        }
        return false;
    }

    /*分页查询*/
    @Override
    public Page<UserDTO> findAllByPage(Long pageNum, Long pageSize, String username) {
        // 1. 查询条件构造器
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        if (StringUtils.hasLength(username)) {
            queryWrapper.like("username", username)
                    .or()
                    .like("phone", username);
        }
//        queryWrapper.eq("enabled",true);
        // 2. 分页查询条件
        Page<UserEntity> page = new Page<>(pageNum, pageSize);

        // 3. 查询结果
        Page<UserEntity> userEntityPage = userDao.selectPage(page, queryWrapper);
        Page<UserDTO> userDTOPage = new Page<>();
        BeanUtils.copyProperties(userEntityPage, userDTOPage);
        List<UserDTO> userDTOS = new ArrayList<>();

        // 4. 添加用户拥有的角色
        for (UserEntity userEntity : userEntityPage.getRecords()) {
            UserDTO userDTO = new UserDTO();
            BeanUtils.copyProperties(userEntity, userDTO);
            // 4.1 查询用户拥有的角色，并赋值
            userDTO.setRoles(roleDao.getRolesByUid(userDTO.getId()));
            // 4.2 设置用户密码为null, 不让前端获取
            userDTO.setPassword("******");
            userDTOS.add(userDTO);
        }
        userDTOPage.setRecords(userDTOS);
        return userDTOPage;
    }

    /*单个属性更新*/
    @Override
    public boolean patchUser(Long id, int enabled) {
        return userDao.patchUser(id, enabled) > 0;
    }

    /**
     * 给用户分配角色
     */
    @Override
    public boolean setRolesForUser(Long userId, String roleIds) {
        // 删除关联表中的数据
        userDao.deleteRelation(userId);
        if(!roleIds.isEmpty()){
            // 新增关联表中的数据
            List<Long> roleIdList = new ArrayList<>();
            String[] split = roleIds.split(",");
            for (String s : split) {
                roleIdList.add(Long.parseLong(s));
            }
            return userDao.setRolesForUser(userId, roleIdList) > 0;
        }
        return true;
    }

}
